<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑Item</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <a href="/dashboard" class="text-gray-500 hover:text-gray-700 mr-4">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                        </svg>
                    </a>
                    <h1 class="text-xl font-semibold text-gray-900">编辑Item</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="logoutBtn" class="text-gray-500 hover:text-gray-700 text-sm">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-4xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        <div class="bg-white rounded-lg shadow-sm border p-6">
            <form id="editItemForm">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <label for="itemType" class="block text-sm font-medium text-gray-700 mb-2">类型 *</label>
                        <select id="itemType" name="type" required 
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="task">任务</option>
                            <option value="issue">问题</option>
                            <option value="requirement">需求</option>
                        </select>
                    </div>
                    <div>
                        <label for="itemPriority" class="block text-sm font-medium text-gray-700 mb-2">优先级</label>
                        <select id="itemPriority" name="priority" 
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="low">低</option>
                            <option value="medium" selected>中</option>
                            <option value="high">高</option>
                            <option value="urgent">紧急</option>
                        </select>
                    </div>
                </div>

                <div class="mb-6">
                    <label for="itemTitle" class="block text-sm font-medium text-gray-700 mb-2">标题 *</label>
                    <input type="text" id="itemTitle" name="title" required 
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="请输入Item标题">
                </div>

                <div class="mb-6">
                    <label for="itemDescription" class="block text-sm font-medium text-gray-700 mb-2">描述</label>
                    <textarea id="itemDescription" name="description" rows="4"
                              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                              placeholder="请输入Item描述"></textarea>
                </div>

                <div class="mb-6">
                    <label for="itemAssignee" class="block text-sm font-medium text-gray-700 mb-2">负责人</label>
                    <select id="itemAssignee" name="assignee_id" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">未分配</option>
                        <option value="1">管理员</option>
                        <option value="2">开发者</option>
                        <option value="3">测试员</option>
                    </select>
                </div>

                <!-- 图片上传区域 -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">相关图片</label>
                    
                    <!-- 上传方式说明 -->
                    <div class="mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                        <div class="flex items-center space-x-2 text-sm text-blue-700">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <span>支持三种方式上传图片：点击选择、拖拽文件、剪贴板粘贴 (Ctrl+V)</span>
                        </div>
                    </div>
                    
                    <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-400 hover:bg-blue-50 transition-all duration-200 focus-within:ring-2 focus-within:ring-blue-500" 
                         id="imageDropZone" tabindex="0">
                        <div class="space-y-4">
                            <svg class="mx-auto h-16 w-16 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                                <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                            </svg>
                            <div class="space-y-2">
                                <div class="text-lg font-medium text-gray-700">上传图片</div>
                                <div class="text-sm text-gray-600">
                                    <span class="font-medium text-blue-600 hover:text-blue-500 cursor-pointer underline" id="uploadTrigger">点击选择文件</span>
                                    <span class="mx-2">或</span>
                                    <span class="font-medium text-blue-600">拖拽图片到此处</span>
                                </div>
                                <div class="text-sm text-gray-500">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                        <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4"></path>
                                        </svg>
                                        支持剪贴板粘贴 (Ctrl+V)
                                    </span>
                                </div>
                            </div>
                        </div>
                        <input type="file" id="fileInput" multiple accept="image/*" class="hidden">
                    </div>
                    
                    <!-- 现有图片显示区域 -->
                    <div id="existingImages" class="mt-4">
                        <h4 class="text-sm font-medium text-gray-700 mb-2">现有图片</h4>
                        <div id="existingImagesContainer" class="grid grid-cols-2 md:grid-cols-4 gap-4">
                            <!-- 现有图片将通过JavaScript动态加载 -->
                        </div>
                    </div>
                    
                    <!-- 新上传图片预览区域 -->
                    <div id="imagePreview" class="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4 hidden">
                        <div class="text-sm font-medium text-gray-700 mb-2">新上传的图片</div>
                        <!-- 图片预览将通过JavaScript动态生成 -->
                    </div>
                </div>

                <!-- 按钮区域 -->
                <div class="flex justify-end space-x-3">
                    <a href="/dashboard" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md">
                        取消
                    </a>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md">
                        保存修改
                    </button>
                </div>
            </form>
        </div>
    </main>

    <script>
        let currentItem = null;
        let uploadedImages = [];

        $(document).ready(function() {
            const itemId = window.location.pathname.split('/')[2]; // /items/{id}/edit
            loadItem(itemId);
            
            // 文件上传触发
            $('#uploadTrigger').click(function() {
                $('#fileInput').click();
            });
            
            $('#imageDropZone').click(function() {
                $('#fileInput').click();
            });
            
            // 文件选择事件
            $('#fileInput').change(function(e) {
                handleFiles(e.target.files);
            });
            
            // 拖拽事件
            $('#imageDropZone').on('dragover', function(e) {
                e.preventDefault();
                $(this).addClass('border-blue-400 bg-blue-50');
            });
            
            $('#imageDropZone').on('dragleave', function(e) {
                e.preventDefault();
                $(this).removeClass('border-blue-400 bg-blue-50');
            });
            
            $('#imageDropZone').on('drop', function(e) {
                e.preventDefault();
                $(this).removeClass('border-blue-400 bg-blue-50');
                handleFiles(e.originalEvent.dataTransfer.files);
            });
            
            // 剪贴板粘贴事件 - 全局监听
            $(document).on('paste', function(e) {
                console.log('Paste event detected'); // 调试信息
                const clipboardData = e.originalEvent.clipboardData;
                if (clipboardData && clipboardData.items) {
                    console.log('Clipboard items:', clipboardData.items.length); // 调试信息
                    for (let i = 0; i < clipboardData.items.length; i++) {
                        const item = clipboardData.items[i];
                        console.log('Clipboard item type:', item.type); // 调试信息
                        if (item.type.indexOf('image') !== -1) {
                            const file = item.getAsFile();
                            if (file) {
                                console.log('Image file found:', file.name, file.size); // 调试信息
                                handleFiles([file]);
                                showNotification('图片已从剪贴板粘贴！', 'success');
                            }
                        }
                    }
                }
            });
            
            // 为上传区域添加焦点，确保能接收粘贴事件
            $('#imageDropZone').attr('tabindex', '0');
            
            // 当上传区域获得焦点时显示提示
            $('#imageDropZone').on('focus', function() {
                $(this).addClass('ring-2 ring-blue-500');
            });
            
            $('#imageDropZone').on('blur', function() {
                $(this).removeClass('ring-2 ring-blue-500');
            });
            
            // 表单提交
            $('#editItemForm').submit(function(e) {
                e.preventDefault();
                
                if (uploadedImages.length === 0) {
                    updateItem();
                } else {
                    // 先上传图片，再更新Item
                    uploadImagesAndUpdateItem();
                }
            });
            
            // 退出登录
            $('#logoutBtn').click(function() {
                $.ajax({
                    url: '/api/logout',
                    method: 'POST',
                    success: function() {
                        window.location.href = '/login';
                    }
                });
            });
        });
        
        function loadItem(itemId) {
            $.ajax({
                url: `/api/items/${itemId}`,
                method: 'GET',
                success: function(response) {
                    currentItem = response.item;
                    populateForm(currentItem);
                    displayExistingImages(currentItem.pictures || []);
                },
                error: function(xhr) {
                    console.error('Failed to load item:', xhr);
                    showNotification('加载Item失败', 'error');
                }
            });
        }
        
        function populateForm(item) {
            $('#itemTitle').val(item.title);
            $('#itemDescription').val(item.description || '');
            $('#itemType').val(item.type);
            $('#itemPriority').val(item.priority);
            $('#itemAssignee').val(item.assignee_id || '');
        }
        
        function displayExistingImages(pictures) {
            const container = $('#existingImagesContainer');
            
            if (pictures.length === 0) {
                container.html('<div class="text-center text-gray-500 py-4">暂无图片</div>');
                return;
            }
            
            container.empty();
            
            pictures.forEach(function(picture) {
                const imageElement = $(`
                    <div class="relative group">
                        <img src="/api/images/${picture.filename}" alt="${picture.original_name}" 
                             class="w-full h-32 object-cover rounded-lg border">
                        <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 rounded-lg flex items-center justify-center">
                            <button class="opacity-0 group-hover:opacity-100 bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded text-xs delete-existing-image-btn" 
                                    data-picture-id="${picture.id}">
                                删除
                            </button>
                        </div>
                        <div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white text-xs p-1 rounded-b-lg">
                            ${picture.original_name}
                        </div>
                    </div>
                `);
                container.append(imageElement);
            });
        }
        
        // 删除现有图片
        $(document).on('click', '.delete-existing-image-btn', function() {
            const pictureId = $(this).data('picture-id');
            if (confirm('确定要删除这张图片吗？')) {
                $.ajax({
                    url: `/api/images/${pictureId}`,
                    method: 'DELETE',
                    success: function() {
                        loadItem(currentItem.id); // 重新加载Item数据
                        showNotification('图片删除成功', 'success');
                    },
                    error: function(xhr) {
                        showNotification('图片删除失败', 'error');
                    }
                });
            }
        });
        
        function handleFiles(files) {
            console.log('Handling files:', files.length); // 调试信息
            let addedCount = 0;
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                console.log('Processing file:', file.name, file.type, file.size); // 调试信息
                
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const imageData = {
                            file: file,
                            dataUrl: e.target.result,
                            id: Date.now() + Math.random()
                        };
                        uploadedImages.push(imageData);
                        addedCount++;
                        updateImagePreview();
                        
                        if (addedCount === 1) {
                            showNotification(`已添加图片: ${file.name}`, 'success');
                        } else if (addedCount > 1) {
                            showNotification(`已添加 ${addedCount} 张图片`, 'success');
                        }
                    };
                    reader.readAsDataURL(file);
                } else {
                    console.log('Skipping non-image file:', file.name); // 调试信息
                }
            }
        }
        
        function updateImagePreview() {
            const container = $('#imagePreview');
            
            if (uploadedImages.length === 0) {
                container.addClass('hidden');
                return;
            }
            
            container.removeClass('hidden');
            container.empty();
            
            // 添加标题
            container.append('<div class="col-span-full text-sm font-medium text-gray-700 mb-2">新上传的图片</div>');
            
            uploadedImages.forEach(function(imageData) {
                const imageElement = $(`
                    <div class="relative group">
                        <img src="${imageData.dataUrl}" alt="预览" 
                             class="w-full h-32 object-cover rounded-lg border">
                        <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 rounded-lg flex items-center justify-center">
                            <button class="opacity-0 group-hover:opacity-100 bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded text-xs remove-image-btn" 
                                    data-image-id="${imageData.id}">
                                删除
                            </button>
                        </div>
                    </div>
                `);
                container.append(imageElement);
            });
        }
        
        // 删除新上传的图片
        $(document).on('click', '.remove-image-btn', function() {
            const imageId = $(this).data('image-id');
            uploadedImages = uploadedImages.filter(img => img.id !== imageId);
            updateImagePreview();
        });
        
        function uploadImagesAndUpdateItem() {
            const formData = new FormData();
            
            uploadedImages.forEach(function(imageData, index) {
                formData.append('images', imageData.file);
            });
            
            $.ajax({
                url: '/api/upload',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    // 图片上传成功后更新Item
                    updateItem(response.filenames || []);
                },
                error: function(xhr) {
                    console.error('Failed to upload images:', xhr);
                    showNotification('图片上传失败', 'error');
                }
            });
        }
        
        function updateItem(imageFilenames = []) {
            const formData = {
                title: $('#itemTitle').val(),
                description: $('#itemDescription').val(),
                type: $('#itemType').val(),
                priority: $('#itemPriority').val(),
                assignee_id: $('#itemAssignee').val() ? parseInt($('#itemAssignee').val()) : null
            };
            
            $.ajax({
                url: `/api/items/${currentItem.id}`,
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    // 如果有新图片，关联图片到Item
                    if (imageFilenames.length > 0) {
                        associateImagesWithItem(currentItem.id, imageFilenames);
                    } else {
                        showNotification('Item更新成功！', 'success');
                        setTimeout(function() {
                            window.location.href = `/items/${currentItem.id}`;
                        }, 1500);
                    }
                },
                error: function(xhr) {
                    const error = xhr.responseJSON?.error || '更新Item失败';
                    showNotification(error, 'error');
                }
            });
        }
        
        function associateImagesWithItem(itemId, imageFilenames) {
            $.ajax({
                url: `/api/items/${itemId}/images`,
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    filenames: imageFilenames
                }),
                success: function(response) {
                    showNotification('Item更新成功！', 'success');
                    setTimeout(function() {
                        window.location.href = `/items/${itemId}`;
                    }, 1500);
                },
                error: function(xhr) {
                    console.error('Failed to associate images:', xhr);
                    showNotification('Item更新成功，但图片关联失败', 'error');
                    setTimeout(function() {
                        window.location.href = `/items/${itemId}`;
                    }, 1500);
                }
            });
        }
        
        function showNotification(message, type) {
            const bgColor = type === 'success' ? 'bg-green-500' : 'bg-red-500';
            const notification = $(`
                <div class="fixed top-4 right-4 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg z-50">
                    ${message}
                </div>
            `);
            
            $('body').append(notification);
            
            setTimeout(function() {
                notification.fadeOut(function() {
                    notification.remove();
                });
            }, 3000);
        }
    </script>
</body>
</html>
